package cn.itcast.config;

import cn.itcast.constant.Constant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author robin
 * @date 25.7.17 17:28
 */
@Configuration
public class SpringAIConfig {

    //把ChatClient放入到容器中
    @Bean
    public ChatClient chatClient(ChatClient.Builder chatClientBuilder, Advisor simpleLoggerAdvisor, Advisor messageChatMemoryAdvisor, Advisor promptChatMemoryAdvisor, Advisor safeGuardAdvisor) {
        //每次请求都会添加系统角色提示词+日志增强
        return chatClientBuilder.defaultSystem(Constant.SYSTEM_ROLE)
                                .defaultAdvisors(simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                                .build();
    }

    //==================================================Advisor=================================

    //日志的Advisor
    @Bean
    public Advisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }

    //基于message聊天记忆增强
    @Bean
    public Advisor messageChatMemoryAdvisor(ChatMemory inMemoryChatMemory) {
        return new MessageChatMemoryAdvisor(inMemoryChatMemory);
    }

    //基于prompt聊天记忆增强
    @Bean
    public Advisor promptChatMemoryAdvisor(ChatMemory inMemoryChatMemory) {
        return new PromptChatMemoryAdvisor(inMemoryChatMemory);
    }

    //安全防护增强
    @Bean
    public Advisor safeGuardAdvisor() {
        List<String> sentiveList = List.of("贩卖病毒", "赌博", "诈骗");
        //SafeGuardAdvisor 优先级是从最小整数加1000,值越小优先级越高
        return new SafeGuardAdvisor(sentiveList, "您提问中涉及违法敏感词，对话结束", Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER);
    }

    //将聊天记忆存储在内存中
    @Bean
    public ChatMemory inMemoryChatMemory() {
        return new InMemoryChatMemory();
    }
}
